package com.lhb.boyixue.user.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lhb.boyixue.user.model.ChatRequestBody;
import com.lhb.boyixue.user.utils.SparkStreamUtil;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class AiChatWebSocketHandler extends TextWebSocketHandler {
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 1. 解析前端发来的JSON字符串
        String payload = message.getPayload();
        ObjectMapper mapper = new ObjectMapper();
        ChatRequestBody data = mapper.readValue(payload, ChatRequestBody.class);

        // 3. 调用AI接口
        SparkStreamUtil.streamChat(data, (String chunk) -> {
            try {
                session.sendMessage(new TextMessage(chunk));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        session.sendMessage(new TextMessage("[[END]]"));
    }
}